﻿package net.wangit.user;

import java.util.Map;

import net.wangit.Element;
import net.wangit.Row;
import net.wangit.User;
import net.wangit.framework.action.ActionMapping;
import net.wangit.user.privilege.PrivilegeUtil;
import net.wangit.util.ArrayUtil;
import net.wangit.view.element.ElementComponent;
import net.wangit.view.unit.UnitComponent;


@SuppressWarnings("serial")
public class RegisteredUser implements User {

	private String id;
	private String name;
	private String organization;
	private String allRoles[];
	private String groups[];
	private Map privileges;
	protected Map properties;

	protected RegisteredUser(String id) {
		this.id = id;
	}

	public String get(String name) {
		return (String) properties.get(name);
	}

	public String getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public String getOrgId() {
		return organization;
	}

	public boolean hasUnitPrivilege(String domain, String unitId,
			String unitShowMode) {
		String key = PrivilegeUtil.getPrivilegeString(domain, "1", unitId,
				unitShowMode);
		return privileges.containsKey(key);
	}

	public boolean hasActionPrivilege(ActionMapping am) {
		return hasElementPrivilege(am.getDomain(), am.getUnitId(), am.getId());
	}

	public boolean hasElementPrivilege(Element element) {
		UnitComponent uc = ((ElementComponent) element).getParent();
		if (uc == null)
			return true;
		else
			return hasElementPrivilege(uc.getDomain(), uc.getId(), element
					.getId());
	}

	public boolean hasDataPrivilege(Object key) {
		return privileges.containsKey(key);
	}

	private boolean hasElementPrivilege(String domain, String unitId,
			String elementId) {
		return privileges.containsKey(PrivilegeUtil.getPrivilegeString(domain,
				"2", unitId, elementId));
	}

	protected void setName(String name) {
		this.name = name;
	}

	protected void set(Map properties) {
		this.properties = properties;
	}

	public void set(String name, String value) {
		properties.put(name, value);
	}

	protected void setPrivileges(Map privileges) {
		this.privileges = privileges;
	}

	protected void setOrganization(String organization) {
		this.organization = organization;
	}

	public Map getPrivileges() {
		return privileges;
	}

	public String[] getAllRoles() {
		return allRoles;
	}

	public boolean containsRole(String roleId) {
		return ArrayUtil.find(allRoles, roleId) >= 0;
	}

	protected void setAllRoles(String allRoles[]) {
		this.allRoles = allRoles;
	}

	public String[] getGroups() {
		return groups;
	}

	public boolean containsGroup(String groupId) {
		return ArrayUtil.find(groups, groupId) >= 0;
	}

	protected void setGroups(String groups[]) {
		this.groups = groups;
	}

	protected void configure(Row row1) {
	}
}
